package com.googlecode.todo_robot;

import com.google.wave.api.*;
import com.googlecode.todo_robot.persistence.DbManager;
import com.googlecode.todo_robot.persistence.DbManagerImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author Fuad Ibrahimov
 * @since 18.12.2009
 */
public class TodoRobotServlet extends AbstractRobotServlet {

  @Override
  public void processEvents(RobotMessageBundle robotMessageBundle) {

    addGadgetIfTodosWavelet(robotMessageBundle);

    for (Event event : robotMessageBundle.getEvents()) {
      if (event.getType() == EventType.DOCUMENT_CHANGED) {
        Wavelet wavelet = robotMessageBundle.getWavelet();
        if (!isTodosWavelet(wavelet)) {
          TextView document = event.getBlip().getDocument();
          processTodos(document, extractTodoAnnotatedRanges(document), event.getModifiedBy());
        }
      }
    }
  }

  private void processTodos(TextView document, List<Range> ranges, String owner) {
    for (Range range : ranges) {
      document.deleteAnnotations(range);
      document.setAnnotation(range, TODO_ROBOT_APPSPOT_COM, SAVED);
      document.setAnnotation(range, STYLE_BACKGROUND_COLOR, YELLOW);
      dbManager.persistTodo(owner, document.getText(range));
      logger.info("Found and persisted annotated todo: [" + document.getText(range) + "]"); // NON-NLS
    }
  }

  private List<Range> extractTodoAnnotatedRanges(TextView document) {
    List<Range> ranges = new ArrayList<Range>();
    for (Annotation annotation : document.getAnnotations()) {
      if (isNewTodo(annotation)) {
        ranges.add(annotation.getRange());
      }
    }
    return ranges;
  }

  private boolean isNewTodo(Annotation annotation) {
    return annotation.getName().equals(TODO_ROBOT_APPSPOT_COM) && annotation.getValue().equals(NEW);
  }

  private void addGadgetIfTodosWavelet(RobotMessageBundle robotMessageBundle) {
    Wavelet wavelet = robotMessageBundle.getWavelet();
    if (robotMessageBundle.wasSelfAdded()) {
      if (isTodosWavelet(wavelet)) {
        Blip blip = wavelet.getRootBlip();
        Gadget gadget = new Gadget(TODO_GADGET_URL);
        blip.getDocument().getGadgetView().append(gadget);
      }
    }
  }

  private boolean isTodosWavelet(Wavelet wavelet) {
    return wavelet.getTitle() != null && wavelet.getTitle().startsWith(TODOS);
  }

  private final DbManager dbManager = new DbManagerImpl();
  private static final String TODOS = "TODOS";
  // TODO delete the old gadget manifest
  private static final String TODO_GADGET_URL = "http://todo-robot.appspot.com/com.googlecode.todo_robot.frontend.TodoGadget/com.googlecode.todo_robot.frontend.client.TodoGadget.gadget.xml";
  private static final Logger logger = Logger.getLogger(TodoRobotServlet.class.getName());
  private static final String TODO_ROBOT_APPSPOT_COM = "todo-robot.appspot.com";
  private static final String NEW = "new";
  private static final String SAVED = "saved";
  private static final String STYLE_BACKGROUND_COLOR = "style/backgroundColor";
  private static final String YELLOW = "rgb(255, 229, 0)";
}
